package router

import (
	"github.com/aberic/gnomon/grope"
	"github.com/pkg/errors"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"gykjgit.dccnet.com.cn/chain/swarm/model"
	"net/http"
)

func RouteStack(hs *grope.GHttpServe) {
	// 仓库相关路由设置
	route := hs.Group("/stack")
	route.Post("/deploy/:stackName", stackDeploy)
	route.Get("/list", stackList)
	route.Get("/process/:stackName", stackProcesses)
	route.Get("/services/:stackName", stackServices)
	route.Get("/remove/:stackName", stackRemove)
}

func stackDeploy(ctx *grope.Context) {
	compose := &proto.Compose{}
	if err := ctx.ReceiveJSON(compose); nil != err {
		responseFailJSON(ctx, errors.Wrap(err, "body error"))
		return
	}
	c, err := model.NewCompose(compose)
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	if err := client.Obtain().Stack().Deploy(c, ctx.Value("stackName")); nil != err {
		_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeFail, ErrMsg: err.Error()})
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess})
}

func stackList(ctx *grope.Context) {
	data, err := client.Obtain().Stack().List()
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: data})
}

func stackProcesses(ctx *grope.Context) {
	data, err := client.Obtain().Stack().Process(ctx.Value("stackName"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: data})
}

func stackServices(ctx *grope.Context) {
	data, err := client.Obtain().Stack().Services(ctx.Value("stackName"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: data})
}

func stackRemove(ctx *grope.Context) {
	if err := client.Obtain().Stack().Remove(ctx.Value("stackName")); nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess})
}
